package cn.newtouch.org.service.impl;

import cn.newtouch.basic.service.impl.BaseServiceImpl;
import cn.newtouch.basic.util.Md5Utils;
import cn.newtouch.basic.util.StrUtils;
import cn.newtouch.org.domain.Employee;
import cn.newtouch.org.mapper.EmployeeMapper;
import cn.newtouch.org.service.IEmployeeService;
import cn.newtouch.user.domain.Logininfo;
import cn.newtouch.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

// @Transactional(readOnly = true,propagation = Propagation.SUPPORTS) 继承性
@Service
public class EmployeetServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    public void save(Employee employee) {

        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密之后的密码
        String md5Pwd = Md5Utils.encrypByMd5(employee.getPassword()+salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);
        //通过员工表获取logininfo 同步logininfo
        Logininfo logininfo = employee2Logininfo(employee);
        logininfoMapper.save(logininfo);

        employee.setLogininfo_id(logininfo.getId());

        //添加操作 需要在员工角色中间表加数据
        employeeMapper.save(employee);

        employeeMapper.saveEmployeeRole(employee.getId(),employee.getRole_id() );

    }

    @Override
    public void update(Employee employee) {
        employeeMapper.update(employee);
        //先通过员工表id删除中间表数据
        employeeMapper.removeEmployeeRole(employee.getId());

        //再通过员工表id和角色id添加中间表数据
        employeeMapper.saveEmployeeRole(employee.getId(),employee.getRole_id() );

    }

    @Override
    public void remove(Long id) {
        //删除员工 需要先删除中间表的数据
        employeeMapper.removeEmployeeRole(id);
        //再删除自己
        employeeMapper.remove(id);

    }

    //通过员工表获取logininfo
    private Logininfo employee2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setType(0);
        return logininfo;
    }

    @Override
    public List<Employee> accept(Long shopId) {
        return employeeMapper.findEmpByShopId(shopId);
    }
}
